package com.jt.interceptor;

/**
 *@author 金帮嘉诚 @date 2021-08-25 星期三 15:39*/

import java.util.ArrayList;
import java.util.List;

/**
 * 拦截器*/
interface Interceptor{
    boolean doPre();
    void doPost();
}
/**处理器*/
interface Handler{
    void doHandle();
}
/**
 * 执行链设计(所有项目中的执行链都是预先设计好的)
 */
class ExecutionChain{
    //拦截器是边缘业务
    private List<Interceptor> interceptors;
    //处理器是核心业务
    private Handler handler;

    public ExecutionChain(List<Interceptor> interceptors,Handler handler){
        this.interceptors=interceptors;
        this.handler=handler;
    }

    public void execute(){
        //1.执行拦截器(Interceptor)中的doPre方法
        for (int i = 0;i<interceptors.size();i++){
            interceptors.get(i).doPre();
        }
        //2.执行处理器(Handler)中的doHandle方法
        handler.doHandle();
        //1.执行拦截器(Interceptor)中的doPost方法
        for (int i = interceptors.size()-1;i>=0;i--){
            interceptors.get(i).doPost();
        }
    }
}

public class ExecutionChainTests {
    public static void main(String[] args) {
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(new Interceptor() {
            @Override
            public boolean doPre() {
                System.out.println("doPre1");
                return false;
            }

            @Override
            public void doPost() {
                System.out.println("doPost1");

            }
        });
        interceptors.add(new Interceptor() {
            @Override
            public boolean doPre() {
                System.out.println("doPre2");
                return false;
            }

            @Override
            public void doPost() {
                System.out.println("doPost2");

            }
        });
        Handler handler = ()->{
            System.out.println("Handler 执行任务.....");
        };
        ExecutionChain chain = new ExecutionChain(interceptors,handler);
        chain.execute();


    }
}
